package com.kcwx.web.controller.system;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.kcwx.common.core.domain.TreeSelect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import com.kcwx.common.annotation.Log;
import com.kcwx.common.constant.UserConstants;
import com.kcwx.common.core.controller.BaseController;
import com.kcwx.common.core.domain.AjaxResult;
import com.kcwx.common.core.domain.entity.SysMenu;
import com.kcwx.common.enums.BusinessType;
import com.kcwx.common.utils.StringUtils;

import com.kcwx.shareddomain.common.dto.DeleteDto;
import com.kcwx.shareddomain.common.dto.DelParaValid;
import com.kcwx.shareddomain.system.query.SysMenuQuery;
import com.kcwx.shareddomain.system.dto.SysMenuEditDto;
import com.kcwx.system.dtomap.SysMenuMap;
import com.kcwx.system.service.ISysMenuService;

/**
 * 菜单信息
 * 
 */
@Api(tags = "系统管理-菜单管理")
@RestController
@RequestMapping("/system/menu")
public class SysMenuController extends BaseController {
	@Autowired
	private ISysMenuService menuService;
	@Autowired
	private SysMenuMap sysMenuMap;
	/**
	 * 新增菜单
	 */
	@ApiOperation("新增")
	@PreAuthorize("@ss.hasPermi('system:menu:add')")
	@Log(title = "新增菜单", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	public AjaxResult add(@Validated @RequestBody SysMenuEditDto dto) {
		SysMenu menu=sysMenuMap.AddDtoToEntity(dto);
		if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) {
			return error("新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
		} else if (menu.getIsFrame() != null && menu.getIsFrame() == 1 && !StringUtils.ishttp(menu.getPath())) {
			return error("新增菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
		}
		menu.setCreateBy(getUsername());
		int rowsAffect=menuService.insertMenu(menu);
		return rowsAffect>0?success():error("新增失败");
	}

	/**
	 * 修改菜单
	 */
	@ApiOperation("修改")
	@PreAuthorize("@ss.hasPermi('system:menu:edit')")
	@Log(title = "修改菜单", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	public AjaxResult edit(@Validated @RequestBody SysMenuEditDto dto) {
		SysMenu menu=sysMenuMap.EditDtoToEntity(dto);
		if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) {
			return error("修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
		} else if (menu.getIsFrame() != null && menu.getIsFrame() == 1 && !StringUtils.ishttp(menu.getPath())) {
			return error("修改菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
		} else if (menu.getId().equals(menu.getParentId())) {
			return error("修改菜单'" + menu.getMenuName() + "'失败，上级菜单不能选择自己");
		}
		menu.setUpdateBy(getUsername());
		int rowsAffect=menuService.updateMenu(menu);
		return rowsAffect>0?success():error("修改失败");
	}

	/**
	 * 删除菜单
	 */
	@ApiOperation("删除")
	@PreAuthorize("@ss.hasPermi('system:menu:remove')")
	@Log(title = "删除菜单", businessType = BusinessType.DELETE)
	@DeleteMapping("/remove")
	public AjaxResult remove(@RequestBody DeleteDto dto) {
		Long id=DelParaValid.validDel(dto);
		if (menuService.hasChildByMenuId(id)) {
			return warn("存在子菜单,不允许删除");
		}
		if (menuService.checkMenuExistRole(id)) {
			return warn("菜单已分配,不允许删除");
		}
		int rowsAffect=menuService.deleteMenuById(id,getUsername());
		return rowsAffect>0?success():error("删除失败");
	}
	/**
	 * 获取菜单列表
	 */
	@ApiOperation("获取菜单列表")
	@PreAuthorize("@ss.hasPermi('system:menu:list')")
	@Log(title = "获取菜单列表", businessType = BusinessType.OTHER)
	@PostMapping("/list")
	public AjaxResult list(@RequestBody SysMenuQuery menu) {
		List<SysMenu> menus = menuService.selectMenuList(menu, getUserId());
		return success(menus);
	}

	/**
	 * 根据id获取详细信息
	 */
	@ApiOperation("根据id获取详细信息")
	@PreAuthorize("@ss.hasPermi('system:menu:query')")
	@Log(title = "根据id获取菜单", businessType = BusinessType.OTHER)
	@GetMapping("/getById")
	public AjaxResult getInfo(Long id) {
		return success(menuService.selectMenuById(id));
	}

	/**
	 * 获取菜单下拉树列表
	 */
	@ApiOperation("获取菜单下拉树列表")
	@Log(title = "获取菜单下拉树列表", businessType = BusinessType.OTHER)
	@PostMapping("/treeselect")
	public AjaxResult treeselect(@RequestBody SysMenuQuery menu) {
		List<SysMenu> menus = menuService.selectMenuList(menu, getUserId());
		return success(menuService.buildMenuTreeSelect(menus));
	}

	/**
	 * 加载对应角色菜单列表树
	 */
	@ApiOperation("加载对应角色菜单列表树")
	@Log(title = "加载对应角色菜单列表树", businessType = BusinessType.OTHER)
	@GetMapping(value = "/roleMenuTreeselect")
	public AjaxResult roleMenuTreeselect(Long roleId) {
		List<SysMenu> menus = menuService.selectMenuList(getUserId());
		List<Long> checkedKeys=menuService.selectMenuListByRoleId(roleId);
		List<TreeSelect> treeMenus=menuService.buildMenuTreeSelect(menus);
		Map<String, Object> dataInfo = new HashMap<>();
		dataInfo.put("checkedKeys", checkedKeys);
		dataInfo.put("menus", treeMenus);
		return success(dataInfo);
	}
}